<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="left" label-width="0px">
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          type="text"
          maxlength="11"
          auto-complete="off"
          placeholder="请输入账户"
          class="iptHeight"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          maxlength="20"
          type="password"
          class="iptHeight"
          auto-complete="off"
          placeholder="请输入密码"
          @keyup.enter="openImgCode"
          show-password
        />
      </el-form-item>
      <!--    <el-form-item>-->
      <!--      <el-input-->
      <!--        v-model="ruleForm.code"-->
      <!--        maxlength="6"-->
      <!--        type="text"-->
      <!--        class="iptHeight graphic"-->
      <!--        auto-complete="off"-->
      <!--        placeholder="请输入图形验证码"-->
      <!--      >-->
      <!--        <template #append>-->
      <!--          <img :src="graphicCode" @click="loadImage" />-->
      <!--        </template>-->
      <!--      </el-input>-->
      <!--    </el-form-item>-->
      <div class="boxBottom">
        <!--        <el-checkbox v-model="ruleForm.rememberMe" style="margin: 0 0 25px 0">自动登录</el-checkbox>-->
        <!--        <div class="forgetPsd" @click="() => $emit('forgetPassword')">忘记密码</div>-->
      </div>

      <el-form-item style="width: 100%">
        <el-button
          :loading="loading.btns"
          type="primary"
          style="width: 100%; border-radius: 27px; height: 54px"
          @click.native.prevent="openImgCode"
        >
          <span v-if="!loading.btns">登录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <Teleport to="body">
      <div class="shell" v-show="dialogVisible" @click.self="dialogVisible = false">
        <div class="container-fluid">
          <div class="form-row">
            <div class="col-12">
              <div class="slidercaptcha card">
                <div class="card-header">
                  <span>请完成安全验证!</span>
                </div>
                <div class="card-body">
                  <div ref="captchaElement" id="captcha"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { UserActionEnum } from '@/store/modules/user/state'
import { useRouter, useRoute } from 'vue-router'

import { encrypt } from '@/utils/rsaEncrypt.js'

defineComponent({
  name: 'AccountLoginComponent'
})
defineEmits(['forgetPassword'])

const store = useStore()
const router = useRouter()
const route = useRoute()
let ruleForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
  code: ''
})

let loading = reactive({
  btns: false
})
const dialogVisible = ref(false)
let captchaInstance = null
onMounted(() => {
  // 加载滑块验证码脚本
  if (window.sliderCaptcha) {
    initializeCaptcha()
  } else {
    loadScript('sources/captcha.min.js', initializeCaptcha)
  }
})
const openImgCode = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) dialogVisible.value = true
  })
}

const loadScript = (src, onLoad) => {
  const script = document.createElement('script')
  script.src = src
  script.onload = onLoad
  document.head.appendChild(script)
}

const initializeCaptcha = () => {
  captchaInstance = window.sliderCaptcha({
    id: 'captcha',
    offset: 10,
    setSrc: function () {
      return import.meta.env.VITE_ENV === 'development'
        ? '/public/images/1.png'
        : location.origin + import.meta.env.VITE_BASE_PREFIX + `images/${Math.floor(Math.random() * 3) + 1}.png`
    },
    failedText: '再划一次',
    onSuccess: () => {
      handleLogin()
      const handler = setTimeout(() => {
        window.clearTimeout(handler)
        captchaInstance.reset()
      }, 200)
    },
    onFail: () => {
      ElMessage({
        message: '验证失败',
        type: 'error'
      })
    }
  })
}
//     remoteUrl: '/code/verify',
// verify: verifyCaptcha,
const verifyCaptcha = async (arr) => {
  let ret = true
  try {
    const res = await request({
      url: '/code/verify',
      method: 'post',
      data: arr
    })
    if (res.code === '500') {
      ret = false
    }
    ret = true
  } catch {
    console.error('校验失败')
  }
  return ret
}
const reset = () => {
  if (captchaInstance) {
    captchaInstance.reset()
  }
}

const rules = {
  username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
  password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]
}

const ruleFormRef = ref()
const graphicCode = ref('')
function loadImage() {
  graphicCode.value = `${import.meta.env.VITE_BASE_URL}/code/captcha?t=` + Math.random()
}
onMounted(() => {
  graphicCode.value = `${import.meta.env.VITE_BASE_URL}/code/captcha?t=` + Date.now()
})
function handleLogin() {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      store
        .dispatch(UserActionEnum.LOGIN, {
          username: encrypt(ruleForm.username),
          password: encrypt(ruleForm.password),
          rememberMe: ruleForm.rememberMe,
          code: ruleForm.code
        })
        .then(() => {
          const targetPath = route.query.redirect || '/'
          router.push({ path: targetPath })
        })
        .catch(() => {
          loadImage()
        })
        .finally(() => {
          dialogVisible.value = false
          loading.btns = false
        })
    } else {
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.boxBottom {
  display: flex;
  justify-content: space-between;
  .forgetPsd {
    font-size: 14px;
    color: #3a68f2;
    cursor: pointer;
  }
}
:deep(.iptHeight) {
  .el-input__wrapper {
    height: 54px;
    padding: 6px;
    .el-input__inner {
      height: 100%;
      padding: 0 11px;
      border-radius: 3px;
    }
  }
}
:deep(.graphic) {
  .el-input-group__append {
    background: none;
    padding: 0 10px;
    img {
      width: 80px;
      height: 50px;
    }
  }
}
.shell {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 11;
  background: rgba(0, 0, 0, 0.7);
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.slidercaptcha {
  margin: 0 auto;
  width: 320px;
  height: 286px;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.125);
  margin-top: 40px;
  background: #fff;
}

.slidercaptcha .card-body {
  padding: 1rem;
}

.slidercaptcha canvas:first-child {
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.slidercaptcha.card .card-header {
  background-image: none;
  background-color: rgba(0, 0, 0, 0.03);
}

.refreshIcon {
  top: -54px;
}
</style>
